package service

import (
	"QHMedLink/model"

	"gorm.io/gorm"
)

// 1. 创建采购需求（带事务）
func CreatePurchase(db *gorm.DB, purchase *model.OrganizationPurchase) error {
	return db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(purchase).Error; err != nil {
			return err
		}
		return nil
	})
}

// 2. 按城市筛选采购需求
func GetPurchasesByCity(db *gorm.DB, city string) ([]model.OrganizationPurchase, error) {
	var purchases []model.OrganizationPurchase
	if err := db.Where("city = ?", city).Find(&purchases).Error; err != nil {
		return nil, err
	}
	return purchases, nil
}

// 3. 更新预算金额
func UpdatePurchaseBudget(db *gorm.DB, id uint, newBudget decimal.Decimal) error {
	return db.Model(&model.OrganizationPurchase{}).
		Where("purchase_id = ?", id).
		Update("budget", newBudget).Error
}

// 4. 复合条件查询（城市+科室）
func GetPurchasesByDept(db *gorm.DB, city, dept string) ([]model.OrganizationPurchase, error) {
	var purchases []model.OrganizationPurchase
	query := db.Where("city = ? AND department = ?", city, dept)
	if err := query.Find(&purchases).Error; err != nil {
		return nil, err
	}
	return purchases, nil
}

// 5. 删除采购需求
func DeletePurchase(db *gorm.DB, id uint) error {
	return db.Model(&model.OrganizationPurchase{}).
		Where("purchase_id = ?", id).
		Update("is_deleted", true).Error
}
